package com.pyb.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

public class SpringWrapper implements ApplicationContextAware {

    private static volatile ApplicationContext context;

    private static final Logger logger = LoggerFactory.getLogger(SpringWrapper.class);

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringWrapper.context = applicationContext;
    }

    public static ApplicationContext getContext() {
        return context;
    }

    public static <T> T getBean(Class<T> type) throws BeansException {
        return context.getBean(type);
    }

    public static Object getBean(String name) throws BeansException {
        return context.getBean(name);
    }

    public static <T> T getBeanWithoutException(String name) throws BeansException {
        try {
            return (T) context.getBean(name);
        } catch (Exception e) {
            logger.error("get bean in spring context error", e);
            return null;
        }
    }
}
